//
//  ZBNavigationBar.m
//  ZBNavigation
//
//  Created by  on 11-11-22.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "ZBNavigationBar.h"
#import "ZBNavigationController.h"
#import "ZBViewControllerProtocol.h"
#import "ZBActivityView.h"
#import "CommonUtil.h"

@interface ZBNavigationBar()
-(void)backButtonAction:(id)sender;
@end

@implementation ZBNavigationBar

@synthesize naviController=_naviController;
@synthesize naviBarRendered=_naviBarRendered;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _backItem = [[UIView  alloc] initWithFrame:CGRectMake(5, 2, 50, 40)];
        UITapGestureRecognizer *tap =[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backButtonAction:)] autorelease];
        [_backItem addGestureRecognizer:tap];
       
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backButton.frame = CGRectMake(5, 4.5, 30, 31);
        [_backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_backItem addSubview:_backButton];
        
        _activityView = [[ZBActivityView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        _activityView.frame = _backButton.frame;
        _activityView.backgroundImage =[IconImage naviButtonImage];
        [_backItem addSubview:_activityView];
        
        [_backItem bringSubviewToFront:_backButton];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{    // Drawing code
    [[IconImage navBarImage] drawInRect:self.bounds];
}


-(void)dealloc
{
    [_backItem release];
    [_backButton release];
    [_activityView release];
    [super dealloc];
}


-(void)backButtonAction:(id)sender
{
    [_naviController popViewControllerAnimated:YES];
}

static BOOL willRefresh = NO;

-(void)navigationItemUpdated:(ZBNavigationItem*)item
{
	if (item!=_currentNavigationItem) {
		return;
	}
    if (!willRefresh) {
        willRefresh = YES;
        [self performSelector:@selector(refreshBar:) withObject:[NSNumber numberWithBool:YES] afterDelay:0.1];
    }
}

-(void)loadingStart:(ZBNavigationItem*)item {
	if (item!=_currentNavigationItem) {
		return;
	}
	[self startLoadingIndicator];
}

-(void)loadingComplete:(ZBNavigationItem*)item{
	if (item!=_currentNavigationItem) {
		return;
	}
	[self stopLoadingIndicator:YES];
}

-(void)refreshBar:(BOOL)animated
{
    willRefresh = NO;
    
    UIView *newLeftItem = nil;
    UIView *newTitleItem = nil;
    UIView *newRightItem = nil;
    
    if ([_topViewController conformsToProtocol:@protocol(ZBViewControllerProtocol)]) {
        id<ZBViewControllerProtocol> zb = (id<ZBViewControllerProtocol>)_topViewController;
          _currentNavigationItem = zb.zbNavigationItem;
        _currentNavigationItem.delegate = self;
          newLeftItem = zb.zbNavigationItem.leftView;
        if (!newLeftItem) {
            newLeftItem = _backItem;
        }
        if (!zb.zbNavigationItem.hideTitle) {
            newTitleItem = zb.zbNavigationItem.titleView;
            if (!newTitleItem) {
                newTitleItem = zb.zbNavigationItem.titleLabel;
            }
        } 
        newRightItem = zb.zbNavigationItem.rightView;
    } else {
        newLeftItem = _topViewController.navigationItem.leftBarButtonItem.customView;
        newTitleItem = _topViewController.navigationItem.titleView;
        newRightItem = _topViewController.navigationItem.rightBarButtonItem.customView;
    }
    BOOL leftItemChanged = _leftItem!=newLeftItem;
    BOOL titleItemChanged = _titleItem!=newTitleItem;
    BOOL rightItemChanged = _rightItem!=newRightItem;
    if (newLeftItem) {
        CGRect rect = newLeftItem.frame;
        rect.origin.x = 5.0f;
        rect.origin.y = (self.bounds.size.height-rect.size.height)/2;
        newLeftItem.frame = rect;
    }
    if (newTitleItem) {
        CGRect rect = newTitleItem.frame;
        rect.origin.x = (self.bounds.size.width-rect.size.width)/2;
        rect.origin.y = (self.bounds.size.height-rect.size.height)/2;
        newTitleItem.frame = rect;
    }
    if (newRightItem) {
        CGRect rect = newRightItem.frame;
        rect.origin.x = self.bounds.size.width - rect.size.width-10.0f;
        rect.origin.y = (self.bounds.size.height-rect.size.height)/2;
        newRightItem.frame = rect;
    }
    if (!animated) {
        if (leftItemChanged) {
            [_leftItem removeFromSuperview];
            _leftItem = newLeftItem;
            if (newLeftItem) {
                [self addSubview:_leftItem];
            }
        }
        if (titleItemChanged) {
            [_titleItem removeFromSuperview];
            _titleItem = newTitleItem;
            if (_titleItem) {
                [self addSubview:_titleItem];
            }
        }
        if (rightItemChanged) {
            [_rightItem removeFromSuperview];
            _rightItem = newRightItem;
            if (_rightItem) {
                [self addSubview:_rightItem];
            }
        }
       [self bringSubviewToFront:_rightItem];
        
        if (_currentNavigationItem.isLoading) {
            [self startLoadingIndicator];
        } else {
            [self stopLoadingIndicator:NO];
        }
        return;
    }
    [UIView transitionWithView:self 
                      duration:0.5 
                       options:UIViewAnimationOptionTransitionCrossDissolve 
                    animations:^{
                        if (leftItemChanged) {
                            [_leftItem removeFromSuperview];
                            _leftItem = newLeftItem;
                            if (newLeftItem) {
                                [self addSubview:_leftItem];
                            }
                        }
                        if (titleItemChanged) {
                            [_titleItem removeFromSuperview];
                            _titleItem = newTitleItem;
                            if (_titleItem) {
                                [self addSubview:_titleItem];
                            }
                        }
                        if (rightItemChanged) {
                            [_rightItem removeFromSuperview];
                            _rightItem = newRightItem;
                            if (_rightItem) {
                                [self addSubview:_rightItem];
                            }
                        }
                        [self bringSubviewToFront:_rightItem];
                    } 
                    completion:^(BOOL finished) {
                        if (_currentNavigationItem.isLoading) {
                            [self startLoadingIndicator];
                        } else {
                            [self stopLoadingIndicator:NO];
                        }
                    }];
//    [UIView animateWithDuration:0.5 
//                     animations:^{
//                         if (leftItemChanged) {
//                             _leftItem.alpha = 0.1;
//                         }
//                         if (titleItemChanged) {
//                             _titleItem.alpha = 0.1;
//                         }
//                         if (rightItemChanged) {
//                             _titleItem.alpha = 0.1;
//                         }
//                     } 
//                     completion:^(BOOL finished) {
//                         if (leftItemChanged) {
//                             [_leftItem removeFromSuperview];
//                             _leftItem = newLeftItem;
//                             if (newLeftItem) {
//                                 [self addSubview:_leftItem];
//                             }
//                         }
//                         if (titleItemChanged) {
//                             [_titleItem removeFromSuperview];
//                             _titleItem = newTitleItem;
//                             if (_titleItem) {
//                                 [self addSubview:_titleItem];
//                             }
//                         }
//                         if (rightItemChanged) {
//                             [_rightItem removeFromSuperview];
//                             _rightItem = newRightItem;
//                             if (_rightItem) {
//                                 [self addSubview:_rightItem];
//                              }
//                         }
//                         [self bringSubviewToFront:_rightItem];
//                         if (leftItemChanged) {
//                            _leftItem.alpha = 0.1;
//                         }
//                         if (titleItemChanged) {
//                            _titleItem.alpha = 0.1;
//                         }
//                         if (rightItemChanged) {
//                             _rightItem.alpha = 0.1;
//                         }
//                         [UIView animateWithDuration:0.5 
//                                          animations:^{
//                                              if (leftItemChanged) {
//                                                    _leftItem.alpha = 1.0;
//                                              }
//                                              if (titleItemChanged) {
//                                                    _titleItem.alpha = 1.0;
//                                              }
//                                              if (rightItemChanged) {
//                                                  _rightItem.alpha = 1.0;
//                                              }
//                                          } 
//                                          completion:nil];
//                     }];
}

-(void)changeTopView:(UIViewController*)newController animated:(BOOL)animated pushOrPop:(BOOL)push
{
    if (_topViewController==newController||newController==nil) {
        return;
    }
    self.naviBarRendered = YES;    
    _topViewController = newController;    
    [self refreshBar:animated];
    
    if (animated) {
        [UIView transitionWithView:_backItem 
                          duration:0.5 
                           options:push?UIViewAnimationOptionTransitionFlipFromRight:UIViewAnimationOptionTransitionFlipFromLeft
                         animations:^(void) {
                             if ([_naviController.viewControllers count]>1) {
                                 [_backButton setImage:[IconImage naviBackImage] forState:UIControlStateNormal];
                                 [_backButton setEnabled:YES];
                             } else {
                                 [_backButton setImage:[IconImage logoImage] forState:UIControlStateNormal];
								_backButton.enabled = NO;
                             } 
                         }completion:nil];
    } else {
        if ([_naviController.viewControllers count]>1) {
            [_backButton setImage:[IconImage naviBackImage] forState:UIControlStateNormal];
			_backButton.enabled = YES;
        } else {
            [_backButton setImage:[IconImage logoImage] forState:UIControlStateDisabled];
			_backButton.enabled = NO;
        }   
    }
}

-(void)startLoadingIndicator
{
    [_activityView startAnimating];
    [_backItem bringSubviewToFront:_activityView];
}

-(void)stopLoadingIndicator:(BOOL)animated
{
	if (animated) {
		[UIView transitionWithView:_backItem duration:0.5 
						   options:UIViewAnimationOptionTransitionFlipFromRight
						animations:^{
							[_activityView stopAnimating];
							[_backItem bringSubviewToFront:_backButton];
						} completion:nil];
	} else {
		[_activityView stopAnimating];
		[_backItem bringSubviewToFront:_backButton];
	}
}

@end
